<script lang="ts" setup>
import { ref } from 'vue'
import { useFetch } from '@/mobile/hooks/fetch';
import InfiniteScroll from '@/mobile/components/InfiniteScroll.vue';
import RecommendDeveloper from './RecommendDeveloper.vue';

const { $fetch } = useFetch();
const listing = ref<any>([]);

let page = 1;
const loading = ref(false);
const finished = ref(false);

const loadMoreData = async () => {
  if (finished.value) {
    return;
  }

  const { isSuccess, data } = await $fetch('/developer/recommend_list', {
    method: 'post',
    data: {
      pageNum: page,
      pageSize: 10,
    },
  });

  if (isSuccess && data?.records?.length) {
    page++;
    listing.value.push(...data.records);
  }
  else {
    finished.value = true;
  }

  loading.value = false;
}

const changeFocus = async (userId: string, isFocus: boolean) => {
  const { isSuccess } = await $fetch(isFocus ? '/user/cancel' : '/user/focus', {
    autoGotoLogin: true,
    data: { userId },
  });

  if (isSuccess) {
    const user = listing.value.find((item: any) => item.userId === userId);
    if (user) {
      user.isFocus = !isFocus; // 切换状态
    }
    console.log('success');
  } else {
    console.log('fail');
  }
};
</script>

<template>
  <section>
    <InfiniteScroll v-model:loading="loading" :finished="finished" @load="loadMoreData">
      <li v-for="(item) in listing" :key="item.userId" class="bg-[#fff] px-20">
        <RecommendDeveloper :data="item" @focus="changeFocus" />
      </li>
    </InfiniteScroll>
  </section>
</template>

<style lang="scss" scoped>
li div:last-child {
  border-bottom: 0;
}
</style>
